<template>
  <el-dialog :model-value="visible" @update:model-value="$emit('update:visible', $event)" :title="isEdit ? '编辑分类' : '新增分类'" width="500px">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="分类名" prop="categoryName">
        <el-input v-model="form.categoryName" />
      </el-form-item>
      <el-form-item label="分类标题" prop="categoryTitle">
        <el-input v-model="form.categoryTitle" />
      </el-form-item>
      <el-form-item label="展示区域" prop="displayArea">
        <el-select v-model="form.displayArea" placeholder="请选择展示区域">
          <el-option label="首页" value="首页" />
          <el-option label="产品信息" value="产品信息" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: Boolean,
  category: { type: Object, default: () => ({}) },
  isEdit: Boolean
})
const emit = defineEmits(['update:visible', 'submit'])

const formRef = ref(null)
const loading = ref(false)
const form = reactive({
  id: '',
  categoryName: '',
  categoryTitle: '',
  displayArea: ''
})

watch(() => props.category, (val) => {
  if (val && Object.keys(val).length) {
    Object.assign(form, val)
  } else {
    Object.assign(form, { id: '', categoryName: '', categoryTitle: '', displayArea: '' })
  }
}, { immediate: true })

const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}
const handleSubmit = async () => {
  await formRef.value.validate()
  loading.value = true
  emit('submit', { ...form })
  loading.value = false
}
const rules = {
  categoryName: [{ required: true, message: '请输入分类名', trigger: 'blur' }],
  displayArea: [{ required: true, message: '请选择展示区域', trigger: 'change' }]
}
</script> 